package com.qiqidream.admin.system.api;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.lang.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qiqidream.admin.common.base.BaseController;
import com.qiqidream.admin.common.entity.CascadeOption;
import com.qiqidream.admin.common.utils.tree.TreeUtil;
import com.qiqidream.admin.system.model.dto.DepartmentDto;
import com.qiqidream.admin.system.model.entity.Department;
import com.qiqidream.admin.system.model.vo.DepartmentVo;
import com.qiqidream.admin.system.service.DepartmentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author QiQiDream
 * @since 2019/12/4 17:41
 */
@RestController
@Api(tags = "系统：部门管理接口")
@RequestMapping("/system/department")
public class DepartmentController extends BaseController {

    @Resource
    DepartmentService departmentService;

    @ApiOperation(value = "查询所有部门")
    @GetMapping("")
    public List<DepartmentVo> getDepartment() {
        return departmentService.getDepartments();
    }

    @ApiOperation(value = "添加部门")
    @PostMapping("")
    public Boolean addDepartment(@RequestBody DepartmentDto departmentDto) {
        Department department = new Department();
        BeanUtils.copyProperties(departmentDto,department);
        return departmentService.save(department);
    }

    @ApiOperation(value = "删除部门")
    @DeleteMapping("/{id}")
    public Boolean removeDepartment(@PathVariable Long id) {
        return departmentService.removeDepartment(id);
    }

    @ApiOperation(value = "编辑部门")
    @PutMapping("")
    public Boolean editDepartment(@RequestBody DepartmentDto departmentDto) {
        Department department = new Department();
        BeanUtils.copyProperties(departmentDto,department);
        return departmentService.updateById(department);
    }

    @ApiOperation(value = "部门-树选择器Option")
    @GetMapping("/option/tree")
    public List<CascadeOption> getDepartmentTreeSelect(@RequestParam(value = "deptName",required = false) String deptName) {
        if (StringUtils.isEmpty(deptName)) {
            List<Department> departments = departmentService.list();
            List<CascadeOption> convert = Convert.convert(new TypeReference<List<CascadeOption>>() {
            }, departments);
            return TreeUtil.getTreeList(0L, convert);
        }
        return departmentService.list(new LambdaQueryWrapper<Department>().like(Department::getName,deptName))
                .stream()
                .map(data -> CascadeOption.builder().id(data.getId()).name(data.getName()).build())
                .collect(toList());
    }
}
